package com.sita.linboard.MainMessage;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sita.linboard.DriverVehicle.VehicleBackBean;
import com.sita.linboard.R;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.calllist.UtilsBean;
import com.sita.linboard.calllist.VehicleListActivity;
import com.sita.linboard.driverInfo.CommonRestBean;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.journey.OrderReceivActivity;
import com.sita.linboard.journey.OrderRequest;
import com.sita.linboard.login.RegisterThirdActivity;
import com.sita.linboard.person.DriverInfoActivity;
import com.sita.linboard.receipt.ReceiptActivity;
import com.sita.linboard.service.LocationService;
import com.sita.linboard.utils.Constants;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {
    final String TAG = getClass().getSimpleName();
    /*用tripid判断是否是同一条行程*/
    private String tripId = "";
    private Button orderlistimg, startVehicle, endVehicle;
    private TextView get_order, get_money, get_closing;
    private ListView paylist;
    private MainListAdapter adapter;
    private LinearLayout setimg;
    private RelativeLayout head_layout;
    private long firstTime = 0;
    //轮播图
    private ViewPager myViewPager;
    private ImageView[] tips;
    private ImageView[] mImageViews;
    private int[] imgIdArray;
    private ViewPagerAdapter viewPagerAdapter;
    private ViewGroup group;
    private int currentPage = 0;//当前显示的页码
    //=======================
    //=======================
    private OrderRemindBroad broadCas;
    private Intent intent;

    public static void getMainIntent(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityCollector.addActivity(this);
        initView();
        setSystemBar(R.color.main_title_bg);
        checkVersion();
        IntentFilter intentFilter = new IntentFilter("com.sita.linboard.PAYINFOMSG");
        broadCas = new OrderRemindBroad();
        registerReceiver(broadCas, intentFilter);
    }

    private void getDirverMsg() {//
        DriverDayMsgRequest request = new DriverDayMsgRequest();
        request.user_id = SpUtils.getString("AccoundID", null, BaseApplication.getContext());
        RestClient.getRestService().driverDayMsg(request, new Callback<DriverDayMsg>() {
            @Override
            public void success(DriverDayMsg driverDayMsg, Response response) {
                if (driverDayMsg.getErrorCode().equals("0") && driverDayMsg.getData() != null)
                    get_order.setText(getString(R.string.main_get_order, driverDayMsg.getData().getOrderNum()));
                get_closing.setText(getString(R.string.main_get_closing, driverDayMsg.getData().getTurnoverRate()));
                get_money.setText("流水 :" + String.valueOf(driverDayMsg.getData().getTurnover()));
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e(TAG, "获取失败");
                Log.e(TAG, error.toString());
            }
        });

    }

    @Override
    public boolean onLongClick(View v) {
        if (v.getId() == R.id.start_vehicle) {
            Constants.isReady = false;
            Constants.isPress = 0;
            startVehicle.setText("出车");
            orderlistimg.setVisibility(View.GONE);
            endVehicle.setVisibility(View.GONE);
            startVehicle.setBackground(ContextCompat.getDrawable(BaseApplication.getContext(), R.drawable.main_confirm_bt));
            //停止服务，停止发送位置
            if (intent == null) {
                intent = new Intent(MainActivity.this, LocationService.class);
            }
            stopService(intent);
        }
        return true;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        get_order = bindView(R.id.finishOrder);
        get_money = bindView(R.id.day_money);
        get_closing = bindView(R.id.success_order);
    }

    @Override
    protected int getId() {
        return R.layout.activity_main;
    }

    private void initView() {
        head_layout = bindView(R.id.head);
        head_layout.setBackgroundColor(ContextCompat.getColor(BaseApplication.getContext(), R.color.main_title_bg));
        orderlistimg = bindView(R.id.orderlist_bt);
        orderlistimg.setOnClickListener(this);
        startVehicle = bindView(R.id.start_vehicle);
        startVehicle.setOnClickListener(this);
        startVehicle.setOnLongClickListener(this);
        endVehicle = bindView(R.id.end_vehicle);
        endVehicle.setOnClickListener(this);
        setimg = bindView(R.id.head_left_img);
        setimg.setVisibility(View.VISIBLE);
        setimg.setOnClickListener(this);
        paylist = bindView(R.id.message);
        adapter = new MainListAdapter(this);
        paylist.setAdapter(adapter);
        myViewPager = bindView(R.id.viewpager);
        group = bindView(R.id.icon_group);
        imgIdArray = new int[]{R.mipmap.home_view_01, R.mipmap.home_view_02, R.mipmap.home_view_03};
        viewPagerAdapter = new ViewPagerAdapter(imgIdArray, this);
        myViewPager.setAdapter(viewPagerAdapter);
        //存放点点的容器
        LinearLayout tipsBox = (LinearLayout) findViewById(R.id.icon_group);
        tips = new ImageView[imgIdArray.length];
        for (int i = 0; i < tips.length; i++) {
            ImageView img = new ImageView(this);
            img.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
            tips[i] = img;
            if (i == 0) {
                img.setBackgroundResource(R.drawable.waite_icon);
            } else {
                img.setBackgroundResource(R.drawable.black_icon);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            params.leftMargin = 5;
            params.rightMargin = 5;
            tipsBox.addView(img, params);

            if (Constants.isReady) {
                startVehicle.setBackground(ContextCompat.getDrawable(this, R.drawable.readydrive));
            }
        }
        myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tips[currentPage].setBackgroundResource(R.drawable.black_icon);
                currentPage = (position % imgIdArray.length);
                tips[position % imgIdArray.length].setBackgroundResource(R.drawable.waite_icon);
                Log.e("Android", position + "s");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.orderlist_bt:
                if (BaseApplication.isNetworkAvailable()) {
                    VehicleListActivity.VehicleListIntent(this);
                } else {
                    ToastUtils.show("网络异常", 3);
                }
                break;
            case R.id.head_left_img:
                DriverInfoActivity.DriverinfoIntent(this);
                break;
            case R.id.start_vehicle:
                //首先检测当前用户是否绑定车辆
                DriverDayMsgRequest request = new DriverDayMsgRequest();
                request.user_id = SpUtils.getString("AccoundID", null, BaseApplication.getContext());
                RestClient.getRestService().AllVehicle(request, new Callback<VehicleBackBean>() {
                    @Override
                    public void success(VehicleBackBean vehicleBackBean, Response response) {
                        if (vehicleBackBean.getErrorCode().equals("0")) {
                            if (vehicleBackBean.getData() != null && vehicleBackBean.getData().size() != 0) {
                                if (!Constants.isReady) {
                                    Constants.isReady = true;
                                    Constants.isPress = 1;//按钮按下，听单中
                                    startVehicle.setText("听单中");
                                    orderlistimg.setVisibility(View.VISIBLE);
                                    endVehicle.setVisibility(View.VISIBLE);
                                    startVehicle.setBackground(ContextCompat.getDrawable(BaseApplication.getContext(), R.drawable.readydrive));
                                    //开始服务，发送实时位置
                                    if (intent == null) {
                                        intent = new Intent(MainActivity.this, LocationService.class);
                                    }
                                    startService(intent);
                                }
                            } else {
                                showDialog();
                            }
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        ToastUtils.show("网络加载异常", 3);
                    }
                });
                //-------------------------------------------------------开始出车

                break;
            case R.id.end_vehicle:
                Constants.isReady = false;
                Constants.isPress = 0;
                startVehicle.setText("出车");
                orderlistimg.setVisibility(View.GONE);
                endVehicle.setVisibility(View.GONE);
                startVehicle.setBackground(ContextCompat.getDrawable(BaseApplication.getContext(), R.drawable.main_confirm_bt));
                //停止服务，停止发送位置
                if (intent == null) {
                    intent = new Intent(MainActivity.this, LocationService.class);
                }
                stopService(intent);
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getDirverMsg();
        isNotLogout();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ActivityCollector.removeActivity(this);
        unregisterReceiver(broadCas);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {                                                    //两次按键小于2秒时，退出应用
                    ActivityCollector.finishAll();
                    finish();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    /********************************************************
     * 未完成订单消息提示
     ********************************************************/
    private void remindDialog(final LastOrderBackBean lastOrderBackBean) {
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.cancelldialog, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        builder.setCancelable(false);
        final AlertDialog dialog = builder.create();
        Log.e(TAG, lastOrderBackBean.getData().getState() + "");
        TextView textView = (TextView) view.findViewById(R.id.dialog_message);
        textView.setText("您有未完成的订单,请继续");
        Button back_orderList_Bt = (Button) view.findViewById(R.id.determine);
        back_orderList_Bt.setText("请继续服务");
        back_orderList_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UtilsBean bean = new UtilsBean();
                bean.setArrival_addr(lastOrderBackBean.getData().getArrival().getAddress());
                bean.setArrival_lat(lastOrderBackBean.getData().getArrival().getLatitude());
                bean.setArrival_lng(lastOrderBackBean.getData().getArrival().getLongitude());
                bean.setCustomer_id(lastOrderBackBean.getData().getCustomer().getAccountId());
                bean.setDeparture_addr(lastOrderBackBean.getData().getDeparture().getAddress());
                bean.setDeparture_lng(lastOrderBackBean.getData().getDeparture().getLongitude());
                bean.setDeparture_lat(lastOrderBackBean.getData().getDeparture().getLatitude());
                bean.setTrip_id(lastOrderBackBean.getData().getTrip_id());
                bean.setMoney(lastOrderBackBean.getData().getPayment());
                Log.e(TAG, lastOrderBackBean.getData().getState() + "");
                if (lastOrderBackBean != null) {
                    switch (lastOrderBackBean.getData().getState()) {
                        case 1:   //接单后没有接到乘客
                            OrderReceivActivity.OrderIntent(MainActivity.this, bean, "1");
                            break;
                        case 2:   //行程开始了
                            OrderReceivActivity.OrderIntent(MainActivity.this, bean, "2");
                            break;
                        case 3:   //行程结束
                            ReceiptActivity.ReceiptIntent(MainActivity.this, bean.getTrip_id(), bean.getCustomer_id(), bean.getDeparture_addr(), bean.getArrival_addr(), bean.getMoney());
                            break;
                    }
                }

                dialog.dismiss();

            }

        });


        dialog.show();
    }

    /********************************************************
     * 异常退出
     ********************************************************/
    private void isNotLogout() {
        OrderRequest request = new OrderRequest();
        request.trip_id = SpUtils.getString("trip_id", null, BaseApplication.getContext());
        RestClient.getRestService().getOneOrder(request, new Callback<LastOrderBackBean>() {
            @Override
            public void success(LastOrderBackBean lastOrderBackBean, Response response) {
                if (lastOrderBackBean.getErrorCode().equals("0")) {
                    if (lastOrderBackBean.getData() != null && (lastOrderBackBean.getData().getState() == 1 ||
                            lastOrderBackBean.getData().getState() == 2 ||
                            lastOrderBackBean.getData().getState() == 3)) {
                        //判断执行的状态
                        // if (lastOrderBackBean.getData().getDriver().getAccountId().equals(SpUtils.getString("AccoundID",null,BaseApplication.getContext()))){
                        remindDialog(lastOrderBackBean);
                        //     }

                    }
                } else {
                }
            }

            @Override
            public void failure(RetrofitError error) {
                LogUtils.d("无异常订单");
            }
        });
    }

    public void setSystemBar(int color) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(color);//通知栏所需颜色

    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    private void showDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("您还未绑定车辆，现在去绑定")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        RegisterThirdActivity.RegisterThirdIntent(MainActivity.this, 3);
                    }
                }).show();
    }

    private void checkVersion() {
        //获取本地版本号
        final String versionName = getVersionInfo().versionName;
        final int versionCode = getVersionInfo().versionCode;
        //获取新版本号
        RestClient.getRestService().getVersion("android", 2, new Callback<CommonRestBean>() {
            @Override
            public void success(CommonRestBean commonRestBean, Response response) {
                if (commonRestBean.getErrorCode().equals("0")) {
                    String str = RestClient.getGson().toJson(commonRestBean.getData());
                    final VersionBean versionBean = RestClient.getGson().fromJson(str, VersionBean.class);
                    if (!versionBean.versionName.equals(versionName) && Integer.parseInt(versionBean.versionCode) > versionCode) {
//                    if (!versionBean.versionName.equals(versionName)) {
                        //提示有新版本
                        String decStr = "新版本功能：";
                        if (versionBean.description.size() != 0) {
                            for (int i = 0; i < versionBean.description.size(); i++) {
                                decStr = decStr + "\n" + versionBean.description.get(i);
                            }
                        } else {
                            decStr = decStr + "\n" + "无";
                        }
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage(decStr);
                        builder.setTitle("发现新版本");
                        builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //跳转到应用市场
                                launchAppDetail();
                            }
                        });
                        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }

                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    /*
 * 获取当前程序的版本号
 */
    private PackageInfo getVersionInfo() {
        PackageManager packageManager = getPackageManager();
        //getPackageName()是当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packInfo;
    }

    /**
     * 启动到app详情界面
     */
    public void launchAppDetail() {
        try {
            Uri uri = Uri.parse("market://details?id=" + "com.sita.linboard");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage("com.tencent.android.qqdownloader");//跳转到应用宝
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setData(Uri.parse("http://app.qq.com/#id=detail&appid=1105740978")); //这里面是需要调转的rul
            it = Intent.createChooser(it, null);
            startActivity(it);
            e.printStackTrace();
        }
    }


    class OrderRemindBroad extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getSerializableExtra("payInfoMsg") != null) {
                PayInfoBackBean payInfo = (PayInfoBackBean) intent.getSerializableExtra("payInfoMsg");
                if (!payInfo.getTripID().equals(tripId)) {
                    adapter.setData((PayInfoBackBean) intent.getSerializableExtra("payInfoMsg"));
                    Log.e(TAG, "支付，系统消息设置成功");
                }
                tripId = payInfo.getTripID();
            }
        }
    }

    /********************************************************
     * ViewPagerAdapter
     ********************************************************/
    public class ViewPagerAdapter extends PagerAdapter {
        private int[] ing;
        private Context context;

        public ViewPagerAdapter(int[] ing, Context context) {
            this.ing = ing;
            this.context = context;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView im = new ImageView(context);
            im.setImageResource(ing[position % ing.length]);
            container.addView(im);
            return im;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // container.removeView();
            //当滑动的数量少于4的时候不需要写

        }

    }

}
